import { onArrayDataChange1, openMessage } from "@/hy_dev_lib/src";
import { ArrowUpOutlined, DeleteOutlined, PaperClipOutlined } from "@ant-design/icons";
import { Button, Input, Row, Space, Upload } from "antd";
import { AnyObject } from "antd/es/_util/type";
import type { UploadRequestOption as RcCustomRequestOptions } from "rc-upload/lib/interface";
import { useRef, useState } from "react";
import { post } from "../useAxios";
import "./index.less";

const { TextArea } = Input;

// export const APP_KEY = "sk-cc80a868c437460ab370aae5ff1fb646";
// export const APP_ID = "391c24e22b824b8a999e8fe3dcf7dce5";

// tkx
export const APP_KEY = "sk-5bbe6fd9a3b74526be2d0be3c374d88a";
export const APP_ID = "76e4db8c8c1d46aea7b62593651012c3";

export const requestUrl = `https://dashscope.aliyuncs.com/api/v1/apps/${APP_ID}/completion`;
// export const requestUrl1 = SYSTEM_GLOBAL.baseURL + "BaiLian/Question2";
export const requestUrl1 = `http://10.32.128.124:9200/dyxhbackstage/User/Question`;
// export const requestUrl1 = `http://10.32.128.124:9235/api/BaiLian/Question`;


// 单次对话信息
interface IDialogueInfo {
  request_id: string;
  text: string;  // 查询的文字内容
  fileList?: any[]; // 上传的文件列表
  result: string; // 返回的结果
}

const useSSE = (url: string = requestUrl, fetchOptions?: RequestInit) => {
  const [loading, setLoading] = useState(false);
  // const [requestIdList, setRequestIdList] = useState<string[]>([]);
  const [sessionId, setSessionId] = useState<string | undefined>();
  const [searchValue, setSearchValue] = useState("");
  const [fileList, setFileList] = useState<any[]>([]);
  // 当前对话的历史记录
  const [dialogueList, setDialogueList] = useState<IDialogueInfo[]>([]);
  const answerBoxRef = useRef<HTMLDivElement>(null)

  const reset = () => {
    setLoading(false);
    setDialogueList([]);
    setSessionId(undefined);
    // setRequestIdList([]);
  };

  const sendAliyunSSERequest = async (params: AnyObject) => {
    setLoading(true);
    // setDialogueList([]);
    const p = {
      input: {
        ...params,
        // prompt: "张三的联系电话是多少",
        // prompt: "定额'平整场地'的定额编号是多少",
        session_id: sessionId,
      },
      parameters: {
        incremental_output: true,
        flow_stream_mode: "agent_format",
        // 文件id
        // session_file_ids: ["file_849d38abaf0348379c531a68f9a38784_11542284"],
        session_file_ids: fileList.map(item => item.fileId),
      },
      debug: {},
    };
    try {
      const response = await fetch(url, {
        method: "POST",
        body: p ? JSON.stringify(p) : null,
        headers: {
          Authorization: `Bearer ${APP_KEY}`,
          "Content-Type": "application/json",
          "X-DashScope-SSE": "enable",
        },
      });
      if (response.body) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        while (true) {
          const { done, value } = await reader.read();
          // console.log(done);
          if (done) {
            setLoading(false);
            break;
          }
          // 解析 SSE 数据
          const chunk = decoder.decode(value);
          const lines = chunk.split("\n");
          const line = lines[3];
          if (line) {
            try {
              const { output, request_id } = JSON.parse(line.slice(5)) || {};
              setSessionId(output.session_id);
              setDialogueList(list => {
                const dialogueInfo = list.find((item) => item.request_id === request_id);
                const newDialogueInfo = {
                  request_id,
                  text: searchValue,
                  fileList,
                  result: (dialogueInfo?.result || "") + output.text
                }
                let newList
                if (dialogueInfo) {
                  newList = onArrayDataChange1(list, setDialogueList, { request_id }, newDialogueInfo, "request_id", false)
                } else {
                  newList = [...list, newDialogueInfo]
                }
                return newList
              })
              // TODO: 先不滚
              // answerBoxRef.current?.scrollTo({
              //   top: answerBoxRef.current.scrollHeight,
              // })
            } catch (error) {
              setLoading(false);
              console.error("JSON.parse error, 请检查返回数据格式！");
            }
          }
        }
      }
    } catch (error: any) {
      setLoading(false);
      console.error(127, error);
    }
  };

  const sendSSERequest = async (params: AnyObject) => {
    setLoading(true);
    // setDialogueList([]);
    console.log(129, fileList, fileList.map(item => item.fileId)?.[0])
    const p = {
      "question": params.prompt,
      "fileId": fileList.map(item => item.fileId)?.[0],
      collection_name: "RAG_datebase_2020定额编号",
    };
    // const queryString = new URLSearchParams(p).toString()
    const formData = new FormData();
    for (const key in p) {
      if (p.hasOwnProperty(key)) {
        // @ts-ignore
        if (p[key]) formData.append(key, p[key]);
      }
    }
    try {
      const response = await fetch(requestUrl1, {
        method: "POST",
        // body: p ? JSON.stringify(p) : null,
        body: formData,
        headers: {
          // Authorization: `Bearer ${APP_KEY}`,
          // "Content-Type": "multipart/form-data",
          "X-DashScope-SSE": "enable",
        },
      });
      if (response.body) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        while (true) {
          const { done, value } = await reader.read();
          // console.log(done);
          if (done) {
            setLoading(false);
            break;
          }
          // 解析 SSE 数据
          const chunk = decoder.decode(value);
          const lines = chunk.split("\n");
          console.log(164, lines)
          const line = lines[0];
          if (line) {
            try {
              const { output, request_id } = JSON.parse(line.slice(5)) || {};
              setSessionId(output.session_id);
              setDialogueList(list => {
                const dialogueInfo = list.find((item) => item.request_id === request_id);
                const newDialogueInfo = {
                  request_id,
                  text: searchValue,
                  fileList,
                  result: (dialogueInfo?.result || "") + output.text
                }
                let newList
                if (dialogueInfo) {
                  newList = onArrayDataChange1(list, setDialogueList, { request_id }, newDialogueInfo, "request_id", false)
                } else {
                  newList = [...list, newDialogueInfo]
                }
                return newList
              })
              // TODO: 先不滚
              // answerBoxRef.current?.scrollTo({
              //   top: answerBoxRef.current.scrollHeight,
              // })
            } catch (error) {
              setLoading(false);
              console.error("JSON.parse error, 请检查返回数据格式！");
            }
          }
        }
      }
    } catch (error: any) {
      setLoading(false);
      console.error(127, error);
    }
  };

  // console.log("sessionId", sessionId);

  const getData = async () => {
    // sendAliyunSSERequest({
    //   prompt: searchValue,
    // });
    sendSSERequest({
      prompt: searchValue,
    })
  };

  const customRequest = async (option: RcCustomRequestOptions) => {
    const { data } = await post("OssUploader/UploadFilesWithPreSignedUrlAsync", {
      files: option.file,
      type: 1,
    })
    // console.log(220, option.file)
    // setFileList([...fileList, {
    //   fileId: data.Body?.Data?.FileId,
    //   name: option.file.name
    // }])
    // 只让传一个先
    setFileList([{
      fileId: data.body?.data?.fileId,
      name: option.file.name
    }])
    openMessage()
  };

  // console.log("fileList", fileList)

  const removeFile = async (fileItem: any, index: number) => {
    // @ts-ignore
    // if (fileItem?.clid) await deleteSynthesizeEnquiryInfo(type, fileItem.id);
    const tmp = [...fileList];
    tmp.splice(index, 1);
    setFileList(tmp);
    openMessage();
  };

  const docAccept = [".doc", ".docx", ".wps", ".ppt", ".pptx", ".xls", ".xlsx", ".md", ".txt", ".pdf"]
  const imgAccept = [".png", ".jpg", ".jpeg", ".bmp", ".gif"]
  const audioAccept = [".aac", ".amr", ".flac", ".flv", ".m4a", ".mp3", ".mpeg", ".ogg", ".opus", ".wav", ".webm", ".wma"]
  const videoAccept = [".mp4", ".mkv", ".avi", ".mov", ".wmv"]

  const inputBox = (
    // useMemo(() => {
    //   return (
    <div className="sse-input-box">
      <TextArea
        variant="borderless"
        disabled={loading}
        value={searchValue}
        placeholder="请输入查询内容..."
        onChange={(e) => {
          setSearchValue(e.target.value);
        }}
        autoSize={{ minRows: 2, maxRows: 3 }}
        onPressEnter={getData}
      ></TextArea>
      <Row align="middle" className="operate-box">
        <div style={{ flex: "auto" }}>
          {
            fileList.map((item, index) => {
              return (
                <Space key={item.fileId} className="file-item" style={{ display: "flex" }}>
                  {item.name}
                  <Button danger type="link" icon={<DeleteOutlined />} onClick={() => removeFile(item, index)}></Button>
                </Space>
              )
            })
          }
        </div>
        <Row align="middle" wrap={false}>
          <Upload
            fileList={[]}
            // fileList={fileList || []}
            onChange={undefined}
            maxCount={10}
            // customRequest={(options) => proFile ? undefined : customRequest(options)}
            customRequest={customRequest}
            showUploadList={false}
            // onRemove={removeFile}
            accept={[...docAccept, ...imgAccept, ...audioAccept, ...videoAccept].join(",")}
          // accept=".doc,.docx"
          // 文档
          // accept=".doc,.docx,.wps,.ppt,.pptx,.xls,.xlsx,.md,.txt,.pdf"
          // 图片
          // accept=".png,.jpg,.jpeg,.bmp,.gif"
          // 音频
          // accept=".aac,.amr,.flac,.flv,.m4a,.mp3,.mpeg,.ogg,.opus,.wav,.webm,.wma"
          // 视频
          // accept=".mp4,.mkv,.avi,.mov,.wmv"
          >
            <Button type="link" className="upload-btn" icon={<PaperClipOutlined />}></Button>
          </Upload>
          <div className="v-divider"></div>
          <Button className="search-btn" loading={loading} onClick={getData}>
            {!loading && <ArrowUpOutlined />}
          </Button>
        </Row>
      </Row>
    </div>
  );
  //   );
  // }, [value, fileList, loading]);

  return {
    dialogueList,
    loading,
    sendAliyunSSERequest,
    reset,
    inputBox,
    answerBoxRef,
  };
};

export default useSSE;
